package com.crom.android.lottebaseball;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import com.mocoplex.adlib.AdlibActivity;
import com.mocoplex.adlib.AdlibConfig;
import com.mocoplex.adlib.AdlibManager.AdlibVersionCheckingListener;

import com.crom.android.lottebaseball.Utils;


public class LottebaseballActivity extends Utils implements OnClickListener {

	Toast mToast;
	final String logTag = "LottebaseballActivity";
	static String today;
	String news = new String(" "); // news popup details
	int date_flag; // for news pop-up checking

	String lotte;
	String away;

	private static LottebaseballActivity INSTANCE = new LottebaseballActivity();

	static String awayName;
	static boolean HOME;
	static int test = 0;

	static public int iningAScore[] = new int[10];
	static public int iningBScore[] = new int[10];
	
	static String allTeamInfo[] = { " "," "," "," "," "," "," "," "," "};

	TextView schedule;
	TextView order;
	TextView otherteam;
	TextView lottenews;
	TextView profile;
	TextView about;
	ImageView settings;
	String version = new String(" ");

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		initAds();
		drawDate("");
		
		Context c = getApplicationContext();   
		try{
			PackageManager packageManager = c.getPackageManager(); 
			//  PackageInfo infor = packageManager.getPackageInfo(mContext.getPackageName(), 0); 
			PackageInfo infor =  packageManager.getPackageInfo(c.getPackageName(), PackageManager.GET_META_DATA); 
			version = infor.versionName;
		}catch(NameNotFoundException e){
			e.printStackTrace(); 
			Log.e(logTag, "not found exception!");
		}
		
		if("2.1.6".equals(version)  || "2.1.5".equals(version)){
			Log.e(logTag, "New Version! 2_1_3");
			new DownloadFilesTaskNews().execute(
					"http://crom991.woobi.co.kr/info_213.html", "", "");
		}
		else if("2.1.2".equals(version)){
			Log.e(logTag, "New Version!");
			new DownloadFilesTaskNews().execute(
					"http://crom991.woobi.co.kr/info_212.html", "", "");
		}else{
			Log.e(logTag, "Old Version!");
			new DownloadFilesTaskNews().execute(
					"http://crom991.woobi.co.kr/info.html", "", "");
		}

		// 실제 광고 호출이 될 adview 를 연결합니다.
		this.setAdsContainer(R.id.ads);

		// Regist();
		Intent i_alarm = new Intent(LottebaseballActivity.this, Alarm.class);
		startService(i_alarm);

		
		// } else {
		// drawScore();
		// }

	}
	


	@Override
	protected void onResume() {
		super.onResume();
		
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// Cancel Notification
		nm.cancel(1234);

		// lotte = notibarService.lotteInfo;
		// away = notibarService.awayteamInfo;

		// if ((lotte==null) || (away==null)){
		// return;
		if (AlarmService_Service.timeCheckNotNoti()) {
			new DownloadFilesTaskCheckScore()
					.execute(
							"http://www.koreabaseball.com/Schedule/PopupGameCastView.aspx",
							"", "");
		} else {
			Log.d("haha", "hahs2");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, 0, "환경설정");

		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		switch (item.getItemId()) {

		case 1:

			// Toast.makeText(this, "select option menu",
			// Toast.LENGTH_SHORT).show();
			Intent i = new Intent(this, settingMenu.class);
			startActivity(i);
			break;

		default:

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void drawDate(String s) {

		Date curMillis;
		int curMonth, curDay, curHour, curMinute, curNoon, curSecond;
		Calendar c;

		c = Calendar.getInstance();
		curMillis = c.getTime();
		curMonth = c.get(Calendar.MONTH);
		curDay = c.get(Calendar.DAY_OF_MONTH);

		TextView date = (TextView) findViewById(R.id.textView1);
		String viewText = (curMonth + 1) + "월 " + curDay + "일 경기";

		// For News Popup
		today = (curMonth + 1) + "/" + curDay;
		date_flag = (curMonth * 100) + curDay;
		if (LottebaseballActivity.HOME)
			viewText += "[사직]";
		else if ("LG".equalsIgnoreCase(LottebaseballActivity.awayName)
				|| "두산".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[잠실]";
		else if ("넥센".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[목동]";
		else if ("KIA".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[광주]";
		else if ("삼성".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[대구]";
		else if ("한화".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[대전]";
		else if ("SK".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[인천]";
		else if ("NC".equalsIgnoreCase(LottebaseballActivity.awayName))
			viewText += "[마산]";

		if (AlarmService_Service.rainGame)
			viewText += " 우천취소";
		else if (AlarmService_Service.endofGame && AlarmService_Service.extendedGame) // 연장&종료일
																			// 경우
																			// 표시함
			viewText += " 종료 (연장)";
		else if (AlarmService_Service.endofGame) // 종료일 경우 표시함
			viewText += " 종료 ";
		else if (AlarmService_Service.extendedGame) // 연장일 경우 표시함
			viewText += " 연장 ";
		
		viewText += s;

		date.setText(viewText);

		schedule = (TextView) findViewById(R.id.schedule_linear);
		order = (TextView) findViewById(R.id.order_linear);
		otherteam = (TextView) findViewById(R.id.otherteam_linear);
		lottenews = (TextView) findViewById(R.id.lottenews_linear);
		profile = (TextView) findViewById(R.id.profile_linear);
		about = (TextView) findViewById(R.id.about_linear);
		settings = (ImageView) findViewById(R.id.imageSettings);

		schedule.setOnClickListener(this);
		order.setOnClickListener(this);
		lottenews.setOnClickListener(this);
		otherteam.setOnClickListener(this);
		profile.setOnClickListener(this);
		about.setOnClickListener(this);
		settings.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {

        if (v.getId() == R.id.button) { // 2013 schedule
            dialog_schdule.dismiss();
        }
        if (v.getId() == R.id.button_about) { // about
            dialog_about.dismiss();
        } else if (v.getId() == R.id.schedule_linear) {
            popup(LottebaseballActivity.this, SCHEDULE);
        } else if (v.getId() == R.id.order_linear) {
            // popup(LottebaseballActivity.this, NOT_SEASON);
            order(LottebaseballActivity.this);
        } else if (v.getId() == R.id.lottenews_linear) {
            // popup(LottebaseballActivity.this, CONSTRUCTING);
            Intent i = new Intent(this, newsWeb.class);
            startActivity(i);
        } else if (v.getId() == R.id.otherteam_linear) {
            boolean alarm_check = AlarmService_Service.timeCheckNotNoti();

			if (!alarm_check)
				popup(LottebaseballActivity.this, NO_TIME);
			else
				draw_otherteam_score();
		} else if (v.getId() == R.id.profile_linear) {
			// popup(LottebaseballActivity.this, CONSTRUCTING);
			Intent i = new Intent(
					this,
					com.crom.android.lottebaseball.profile.SplashDemoActivity.class);
			startActivity(i);
		} else if (v.getId() == R.id.about_linear) {
			popup(LottebaseballActivity.this, ABOUT_LOTTE);
		} else if (v.getId() == R.id.imageSettings) {
			// popup(LottebaseballActivity.this, ABOUT_LOTTE);
			Intent i = new Intent(this, settingMenu.class);
			startActivity(i);
		}
	}

	public void drawScore() {

		Log.d("haha", "hahas3");
		if (LottebaseballActivity.HOME) {
			iningBScore = parseScore(lotte);
			iningAScore = parseScore(away);
		} else {
			iningAScore = parseScore(lotte);
			iningBScore = parseScore(away);
		}

		TextView team1 = (TextView) findViewById(R.id.team1);
		TextView team2 = (TextView) findViewById(R.id.team2);

		TextView iningA[] = new TextView[10];
		TextView iningB[] = new TextView[10];

		iningA[0] = (TextView) findViewById(R.id.iniing1a);
		iningA[1] = (TextView) findViewById(R.id.iniing2a);
		iningA[2] = (TextView) findViewById(R.id.iniing3a);
		iningA[3] = (TextView) findViewById(R.id.iniing4a);
		iningA[4] = (TextView) findViewById(R.id.iniing5a);
		iningA[5] = (TextView) findViewById(R.id.iniing6a);
		iningA[6] = (TextView) findViewById(R.id.iniing7a);
		iningA[7] = (TextView) findViewById(R.id.iniing8a);
		iningA[8] = (TextView) findViewById(R.id.iniing9a);
		iningA[9] = (TextView) findViewById(R.id.iniingRa);

		iningB[0] = (TextView) findViewById(R.id.iniing1b);
		iningB[1] = (TextView) findViewById(R.id.iniing2b);
		iningB[2] = (TextView) findViewById(R.id.iniing3b);
		iningB[3] = (TextView) findViewById(R.id.iniing4b);
		iningB[4] = (TextView) findViewById(R.id.iniing5b);
		iningB[5] = (TextView) findViewById(R.id.iniing6b);
		iningB[6] = (TextView) findViewById(R.id.iniing7b);
		iningB[7] = (TextView) findViewById(R.id.iniing8b);
		iningB[8] = (TextView) findViewById(R.id.iniing9b);
		iningB[9] = (TextView) findViewById(R.id.iniingRb);

		if (LottebaseballActivity.HOME) {

			team1.setText(LottebaseballActivity.awayName);
			team2.setText("롯데");

		} else {
			team2.setText(LottebaseballActivity.awayName);
			team1.setText("롯데");

		}

		for (int i = 0; i < 10; i++) {
			if (iningAScore[i] == -1)
				iningA[i].setText("");
			else
				iningA[i].setText("" + iningAScore[i]);

			if (iningBScore[i] == -1)
				iningB[i].setText("");
			else
				iningB[i].setText("" + iningBScore[i]);
		}
	}
	
	public int parseScoreOther(String info){
		
		int score=0;
		if(info == null)
			return score;
		String[] values = info.split("\n");
		 for(int i=0; i<values.length; i++) {
			
			 if(values[i].contains("run"))
				 score = String2Int(values[i]);	
			
		 }	
		 
		 
		return score;
	}

	public int[] parseScore(String info) {

		int score[] = new int[10];
		int i = 0;

		if (info == null)
			return score;
		String[] values = info.split("\n");

		for (i = 0; i < values.length; i++) {
			// Log.d(logTag, "Split String "+values[i]+" index"+i);
			if (i >= 2 && i <= 5)
				score[i - 2] = String2Int(values[i]);

			if (i >= 7 && i <= 11)
				score[i - 3] = String2Int(values[i]);

			if (values[i].contains("run"))
				score[9] = String2Int(values[i]);

		}

		return score;
	}

	public static LottebaseballActivity getInstance() {

		return INSTANCE;

	}

	public int String2Int(String str) {

		int ret = 0;
		boolean checker = false;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c > 47 && c < 58) {
				ret = (ret * 10) + (c - 48);
				checker = true;
			}

		}

		// Log.d(logTag,"String2Int return Value is " + ret );
		if (checker)
			return ret;
		else
			return -1;
	}

	public void drawPopup() {
		SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
		int saved_flag = pref.getInt("saved_date", 0);

		if (date_flag == saved_flag) // If user select Do not show again during
										// today
			return;

		// Toast.makeText(this, "Before pop-sup"+news,
		// Toast.LENGTH_SHORT).show();
		Builder dlg = new AlertDialog.Builder(LottebaseballActivity.this);

		dlg.setTitle(" 롯데야구 알리미(" + today + ")").setMessage(news)

		.setIcon(R.drawable.news)

		.setPositiveButton("네", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				SharedPreferences pref = getSharedPreferences("pref",
						MODE_PRIVATE);
				SharedPreferences.Editor editor = pref.edit();
				editor.putInt("saved_date", date_flag);
				editor.commit();
			}
		}).setNegativeButton("아니요", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

			}
		}).show();
	}

	public void draw_otherteam_score() {
		// Toast.makeText(this, "Before pop-sup"+news,
		// Toast.LENGTH_SHORT).show();

		String otherteam = "";

		for (int i = 0; i < 8; i++) {

			if (LottebaseballActivity.allTeamInfo[i] != " ") {
				otherteam += LottebaseballActivity.allTeamInfo[i];
			}

			if ((i % 2) == 0)
				otherteam += "  Vs  ";
			if ((i % 2) == 1)
				otherteam += "\n";

		}

		Builder dlg = new AlertDialog.Builder(LottebaseballActivity.this);

		dlg.setTitle(" 타구장 소식").setMessage(otherteam)

		.setIcon(R.drawable.news)

		.setNegativeButton("확인", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

			}
		}).show();

	}

	public String parseName(String info) {

		String name = " ";
		// Log.d(logTag, "ParseName "+info);
		if (info == null)
			return name;
		String[] values = info.split("\n");
		/*
		 * for(int i=0; i<values.length; i++) { Log.d(logTag,
		 * "Split String "+values[i]); }
		 */
		int index = values[1].indexOf('>');

		name = values[1].substring(index + 1, index + 3);
		// Log.d(logTag, "Split String "+name);
		if (name.contains("KI"))
			return "KIA";

		return name;
	}

	public void initAds() {
		AdlibConfig.getInstance().bindPlatform("INMOBI",
				"com.crom.android.lottebaseball.ad.SubAdlibAdViewInmobi");

		AdlibConfig.getInstance().bindPlatform("ADAM",
				"com.crom.android.lottebaseball.ad.SubAdlibAdViewAdam");
		AdlibConfig.getInstance().bindPlatform("CAULY",
				"com.crom.android.lottebaseball.ad.SubAdlibAdViewCauly");
		AdlibConfig.getInstance().bindPlatform("NAVER",
				"com.crom.android.lottebaseball.ad.SubAdlibAdViewNaverAdPost");
		AdlibConfig.getInstance().setAdlibKey("4fee6daa0cf23b59b45f5275");

		AdlibConfig.getInstance().setAdInfo("M", "10", "31.111", "127.111");

	}

	private class DownloadFilesTaskNews extends
			AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... urls) {

			URL nURL;
			InputStream html;
			Source source;
			String addr = null;
			String content = new String(" ");

			addr = urls[0];

			try {

				nURL = new URL(addr);
				html = nURL.openStream();
				source = new Source(new InputStreamReader(html, "EUC-KR"));
				source.fullSequentialParse();
				List<Element> lis = source.getAllElements(HTMLElementName.LI);

				StringBuilder sb = new StringBuilder();
				for (Element li : lis) {
					sb.append(li.getContent().getTextExtractor().toString());
					sb.append("\n");
				}

				content = sb.toString();

			} catch (MalformedURLException e) {
				e.printStackTrace();
				return false;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			news = content;
			return true;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("ASYNC", "result = " + result);
			if (result != null) {
				;
			}
			drawPopup();
		}

	}

	private class DownloadFilesTaskCheckScore extends
			AsyncTask<String, Integer, Boolean> {
		protected Boolean doInBackground(String... urls) {

			final Calendar c = Calendar.getInstance();
			int mDay = c.get(Calendar.DAY_OF_WEEK);/*
													 * sunday:0 moday:1 ...
													 * saturday:7
													 */
			if (java.util.Calendar.MONDAY == mDay)
				return false;

			int count = urls.length;
			long totalSize = 0;
			URL nURL;
			InputStream html;
			Source source;
			String addr = null;

			addr = urls[0];

			try {

				nURL = new URL(addr);
				html = nURL.openStream();
				source = new Source(new InputStreamReader(html, "UTF-8"));
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return false;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

			Element tableSub[] = new Element[4];
			ArrayList<Element> trListSub = new ArrayList<Element>();
			ArrayList<String> trStringListSub = new ArrayList<String>();
			// boolean HOMEGAME_sub = false; // 홈경기인가

			try { // 2013.02.04 IndexOutOfBoundsException
				// Game Get Value from Table information
				tableSub[0] = (Element) source.getAllElements(
						HTMLElementName.TABLE).get(0);
				tableSub[1] = (Element) source.getAllElements(
						HTMLElementName.TABLE).get(2);
				tableSub[2] = (Element) source.getAllElements(
						HTMLElementName.TABLE).get(4);
				tableSub[3] = (Element) source.getAllElements(
						HTMLElementName.TABLE).get(6);
			} catch (IndexOutOfBoundsException e) {
				// TODO Auto-generated catch block
				Log.d(logTag, "IndexOutOfBoundsException !!" + e);
				e.printStackTrace();
				return false;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d(logTag, "Exception 5" + e);
				e.printStackTrace();
				return false;
			}

			for (int i = 0; i < 4; i++) {
				trListSub.add((Element) tableSub[i].getAllElements(
						HTMLElementName.TR).get(1));
				trListSub.add((Element) tableSub[i].getAllElements(
						HTMLElementName.TR).get(2));
			}

			for (int i = 0; i < 8; i++) {
				trStringListSub.add(trListSub.get(i).toString());
				// Log.d(logTag, "In getCurrentScroe TR Litt:"+i+" "+
				// trStringList.get(i));
			}
			int lotteIndex = -1;

			for (int i = 0; i < 8; i++) {
				if (trStringListSub.get(i).contains("롯데")) {
					lotteIndex = i;
					break;
				}
				
			}
			
			//other team score	
			for(int i=0; i<8; i++){
				
				allTeamInfo[i] = parseName (trStringListSub.get(i));
				int tmp_score = parseScoreOther(trStringListSub.get(i));
				allTeamInfo[i] += " ";
				allTeamInfo[i] += String.valueOf(tmp_score);				
			}
			
			if( lotteIndex == -1){ // check no game day
				Log.d(logTag, "NO GAMEDAY");
				return false;
			}

			int cancleIndex = 0;
			switch (lotteIndex) {

			case 0:
			case 1:
				cancleIndex = 1;
				break;
			case 2:
			case 3:
				cancleIndex = 4;
				break;
			case 4:
			case 5:
				cancleIndex = 7;
				break;
			case 6:
			case 7:
				cancleIndex = 10;
				break;

			}

			if ((lotteIndex % 2) == 1) {
				// HOMEGAME_sub = true;
				LottebaseballActivity.HOME = true;
			} else {
				// HOMEGAME_sub = false;
				LottebaseballActivity.HOME = false;

			}

			lotte = trStringListSub.get(lotteIndex);

			if (LottebaseballActivity.HOME)
				away = trStringListSub.get(lotteIndex - 1);
			else
				away = trStringListSub.get(lotteIndex + 1);

			LottebaseballActivity.awayName = parseName(away);

			return true;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("ASYNC", "result = " + result);
			if (result == false) {
				Log.d(logTag, "NO GAMEDAY2");
				String s = " 없는날";
				drawDate(s);
			}else{

				if ((lotte != null) && (away != null))
					drawScore();
				else
					Log.d("haha", "haha");
			}
		}

	}

}